package com.szqhyxj.youxiangju.biz.plan;

import android.os.Parcel;
import android.os.Parcelable;
import android.util.Log;

import com.google.gson.annotations.SerializedName;
import com.szqhyxj.youxiangju.sys.BaseResult;
import com.szqhyxj.youxiangju.sys.RetrofitFacade;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Query;

public class PlanModel {

    //消费
    public static final String CONSUME = "consumeType";
    //还款
    public static final String REFUND = "refundType";

    //返回当前账单列表
    public static final String PRESENT = "present";

    //返回历史账单列表
    public static final String HISTORY = "history";


    public interface PlanService {
        @GET("plan/detail")
        Observable<BaseResult<PlanDetail>> getPlanDetail(@Query("planId") String planId);

        @FormUrlEncoded
        @POST("plan/add")
        Observable<BaseResult<PlanCreateResult>> create(
                @Field("totalAmount") BigDecimal totalAmount,
                @Field("cardNo") String cardNo,
                @Field("planLength") int planLength,
                @Field("ratio") int ratio
        );

        @FormUrlEncoded
        @POST("plan/apply")
        Observable<BaseResult<Object>> apply(
                @Field("planId") String planId
        );

        @GET("plan/detail")
        Observable<BaseResult<PlanDetail>> detail(
                @Query("planId") String planId
        );

        @GET("plan/preview")
        Observable<BaseResult<PlanDetail>> preview(
                @Query("planId") String planId
        );

        @GET("plan/listRunning")
        Observable<BaseResult<PlanList>> getPlanListRunning(
                @Query("pageSize") int pageSize,
                @Query("pageNumber") int pageNumber
        );

        @GET("plan/listFailure")
        Observable<BaseResult<PlanList>> getPlanListFailure(
                @Query("pageSize") int pageSize,
                @Query("pageNumber") int pageNumber
        );

        @GET("plan/listSuccess")
        Observable<BaseResult<PlanList>> getPlanListSuccess(
                @Query("pageSize") int pageSize,
                @Query("pageNumber") int pageNumber
        );

        @GET("plan/listPaused")
        Observable<BaseResult<PlanList>> getPlanListPaused(
                @Query("pageSize") int pageSize,
                @Query("pageNumber") int pageNumber
        );

        //获取计划
        @FormUrlEncoded
        @POST("v3/plan/appList")
        Observable<BaseResult<List<RowItem>>> getPlanList(
                @Field("status") int status
        );

    }

    private static PlanService planService = RetrofitFacade.Companion.getRetrofit().create(PlanService.class);

    public static Observable<BaseResult<PlanCreateResult>> create(PlanCreateEntity planCreateEntity) {
        return planService.create(
                new BigDecimal(planCreateEntity.getTotalAmount()),
                planCreateEntity.getCardNo(),
                planCreateEntity.getPlanLength(),
                planCreateEntity.getRatio()
        );
    }

    public static Observable<BaseResult<Object>> apply(String planId) {
        return planService.apply(planId);
    }

    public static Observable<BaseResult<PlanDetail>> detail(String planId) {
        return planService.detail(planId);
    }

    public static Observable<BaseResult<PlanDetail>> preview(String planId) {
        return planService.preview(planId);
    }

    public static Observable<BaseResult<PlanDetail>> getPlanDetail(String planId) {
        return RetrofitFacade.Companion.getRetrofit().create(PlanModel.PlanService.class).getPlanDetail(planId);
    }

    //获取正在执行中计划列表
    public static Observable<BaseResult<PlanList>> getPlanList(QueryPlanEntity entity) {
        return planService.getPlanListRunning(entity.getPageSize(), entity.getPageNumber());
    }


    //获取失败计划列表
    public static Observable<BaseResult<PlanList>> getPlanListFailure(QueryPlanEntity entity) {
        return planService.getPlanListFailure(entity.getPageSize(), entity.getPageNumber());
    }

    //获取成功计划列表
    public static Observable<BaseResult<PlanList>> getPlanListSuccess(QueryPlanEntity entity) {
        return planService.getPlanListSuccess(entity.getPageSize(), entity.getPageNumber());
    }


    //获取暂停计划列表
    public static Observable<BaseResult<PlanList>> getPlanListPaused(QueryPlanEntity entity) {
        return planService.getPlanListPaused(entity.getPageSize(), entity.getPageNumber());
    }

    //获取计划列表
    // 1 进行中 / 2 暂停/ 3 意外结束 / 4 正常结束
    public static Observable<BaseResult<List<RowItem>>> getPlanLists(int status){
          return RetrofitFacade.Companion.getMockretrofit().create(PlanService.class).getPlanList(status);
    }


    public static class PlanParticularsDayEntity {
        private long time;
        private int refundNum;
        private int expenditureNum;

        public long getTime() {
            return time;
        }

        public void setTime(long time) {
            this.time = time;
        }

        public int getRefundNum() {
            return refundNum;
        }

        public void setRefundNum(int refundNum) {
            this.refundNum = refundNum;
        }

        public int getExpenditureNum() {
            return expenditureNum;
        }

        public void setExpenditureNum(int expenditureNum) {
            this.expenditureNum = expenditureNum;
        }
    }

    public static class PlanLengthRange {
        int start;

        int end;

        public PlanLengthRange(int start, int end) {
            this.start = start;
            this.end = end;
        }

        public int getStart() {
            return start;
        }

        public void setStart(int start) {
            this.start = start;
        }

        public int getEnd() {
            return end;
        }

        public void setEnd(int end) {
            this.end = end;
        }
    }


    public static class PlanCreateResult {

        @SerializedName("planId")
        private String planId;

        public void setPlanId(String planId) {
            this.planId = planId;
        }

        public String getPlanId() {
            return planId;
        }

        @Override
        public String toString() {
            return
                    "PlanCreateResult{" +
                            "planId = '" + planId + '\'' +
                            "}";
        }
    }

    public static class PlanCreateEntity implements Parcelable {

        @SerializedName("totalAmount")
        private int totalAmount;

        @SerializedName("cardNo")
        private String cardNo;

        @SerializedName("planLength")
        private int planLength;

        @SerializedName("ratio")
        private Integer ratio;

        public String getBtName() {
            return btName;
        }

        public void setBtName(String btName) {
            this.btName = btName;
        }

        @SerializedName("btName")
        private String btName;

        public void setTotalAmount(int totalAmount) {
            this.totalAmount = totalAmount;
        }

        public int getTotalAmount() {
            return totalAmount;
        }

        public void setCardNo(String cardNo) {
            this.cardNo = cardNo;
        }

        public String getCardNo() {
            return cardNo;
        }

        public void setPlanLength(int planLength) {
            this.planLength = planLength;
        }

        public int getPlanLength() {
            return planLength;
        }

        public void setRatio(Integer ratio) {
            this.ratio = ratio;
        }

        public Integer getRatio() {
            return ratio;
        }

        @Override
        public String toString() {
            return
                    "PlanCreateResponse{" +
                            "totalAmount = '" + totalAmount + '\'' +
                            ",cardNo = '" + cardNo + '\'' +
                            ",planLength = '" + planLength + '\'' +
                            ",ratio = '" + ratio + '\'' +
                            "}";
        }

        public PlanCreateEntity() {
        }

        @Override
        public int describeContents() {
            return 0;
        }

        @Override
        public void writeToParcel(Parcel dest, int flags) {
            dest.writeInt(this.totalAmount);
            dest.writeString(this.cardNo);
            dest.writeInt(this.planLength);
            dest.writeInt(this.ratio);
            dest.writeString(this.btName);
        }

        protected PlanCreateEntity(Parcel in) {
            this.totalAmount = in.readInt();
            this.cardNo = in.readString();
            this.planLength = in.readInt();
            this.ratio = in.readInt();
            this.btName = in.readString();
        }

        public static final Creator<PlanCreateEntity> CREATOR = new Creator<PlanCreateEntity>() {
            @Override
            public PlanCreateEntity createFromParcel(Parcel source) {
                return new PlanCreateEntity(source);
            }

            @Override
            public PlanCreateEntity[] newArray(int size) {
                return new PlanCreateEntity[size];
            }
        };
    }

    public static void convertToDisplay(PlanDetail planDetailBaseResult, List<List<Map<String, TasksItem>>> tasksList, List<PlanModel.PlanParticularsDayEntity> entityList) {
        int day = 0;
        int repayCount = 0;
        for (TasksItem tasksBean : planDetailBaseResult.getTasks()) {
            int time = Integer.parseInt(timeStamp2Date(tasksBean.getToExecuteTime()));

            if (day < time) {
                day = time;
                PlanModel.PlanParticularsDayEntity entity = new PlanModel.PlanParticularsDayEntity();
                entity.setTime(tasksBean.getToExecuteTime());
                entityList.add(entity);
                Log.w("123", day + "");
                Log.w("123", entityList.size() + "");
                List<Map<String, TasksItem>> mapList = new ArrayList<>();
                tasksList.add(mapList);
                Log.w("===========", tasksList.size() + "");
                //如果当前的第一笔是还款，提前创建一条Map<String, TasksItem>数据
                if (tasksBean.getType() == TaskType.REPAY.getCode()) {
                    Map<String, TasksItem> map = new HashMap<>();
                    mapList.add(map);
                }
            }

            PlanModel.PlanParticularsDayEntity entity = entityList.get(entityList.size() - 1);
            List<Map<String, TasksItem>> mapList = tasksList.get(tasksList.size() - 1);


            if (tasksBean.getType() == TaskType.PAY.getCode()) {
                if (tasksBean.getStatus() == PlanTaskStatus.SUCCESS.getCode()) {
                    entity.setExpenditureNum(entity.getExpenditureNum() + 1);
                }
                Map<String, TasksItem> map = new HashMap<>();
                map.put(CONSUME, tasksBean);
                mapList.add(map);
            } else if (tasksBean.getType() == TaskType.REPAY.getCode()) {
                repayCount = repayCount + 1;
                if (tasksBean.getStatus() == PlanTaskStatus.SUCCESS.getCode()) {
                    entity.setRefundNum(entity.getRefundNum() + 1);
                }
                if (mapList.size() == 0) {

                } else {
                    Map<String, TasksItem> map = mapList.get(mapList.size() - 1);
                    map.put(REFUND, tasksBean);
                }

            } else {

            }
        }
    }



    public static void convertToDisplayPreview(PlanDetail planDetailBaseResult, List<List<Map<String, TasksItem>>> tasksList, List<PlanModel.PlanParticularsDayEntity> entityList) {
        int day = 0;
        int repayCount = 0;
        for (TasksItem tasksBean : planDetailBaseResult.getTasks()) {
            int time = Integer.parseInt(timeStamp2Date(tasksBean.getToExecuteTime()));

            if (day < time) {
                day = time;
                PlanModel.PlanParticularsDayEntity entity = new PlanModel.PlanParticularsDayEntity();
                entity.setTime(tasksBean.getToExecuteTime());
                entityList.add(entity);

                List<Map<String, TasksItem>> mapList = new ArrayList<>();
                tasksList.add(mapList);

                //如果当前的第一笔是还款，提前创建一条Map<String, TasksItem>数据
                if (tasksBean.getType() == TaskType.REPAY.getCode()) {
                    Map<String, TasksItem> map = new HashMap<>();
                    mapList.add(map);
                }
            }

            PlanModel.PlanParticularsDayEntity entity = entityList.get(entityList.size() - 1);
            List<Map<String, TasksItem>> mapList = tasksList.get(tasksList.size() - 1);


            if (tasksBean.getType() == TaskType.PAY.getCode()) {

                entity.setExpenditureNum(entity.getExpenditureNum() + 1);

                Map<String, TasksItem> map = new HashMap<>();
                map.put(CONSUME, tasksBean);
                mapList.add(map);
            } else {
                repayCount = repayCount + 1;

                entity.setRefundNum(entity.getRefundNum() + 1);

                Map<String, TasksItem> map = mapList.get(mapList.size() - 1);
                map.put(REFUND, tasksBean);
            }
        }
    }

    /**
     * 时间戳转换精确到天的字符串
     *
     * @param seconds
     * @param
     * @return
     */
    public static String timeStamp2Date(long seconds) {
        String format = "yyyyMMdd";
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new Date(seconds));
    }

    public static class QueryPlanEntity {

        @SerializedName("pageNumber")
        private int pageNumber;

        @SerializedName("merchantId")
        private int merchantId;

        @SerializedName("pageSize")
        private int pageSize;

        @SerializedName("cardNo")
        private String cardNo;

        public void setPageNumber(int pageNumber) {
            this.pageNumber = pageNumber;
        }

        public int getPageNumber() {
            return pageNumber;
        }

        public void setMerchantId(int merchantId) {
            this.merchantId = merchantId;
        }

        public int getMerchantId() {
            return merchantId;
        }

        public void setPageSize(int pageSize) {
            this.pageSize = pageSize;
        }

        public int getPageSize() {
            return pageSize;
        }

        public void setCardNo(String cardNo) {
            this.cardNo = cardNo;
        }

        public String getCardNo() {
            return cardNo;
        }

        @Override
        public String toString() {
            return
                    "QueryPlanEntity{" +
                            "pageNumber = '" + pageNumber + '\'' +
                            ",merchantId = '" + merchantId + '\'' +
                            ",pageSize = '" + pageSize + '\'' +
                            ",cardNo = '" + cardNo + '\'' +
                            "}";
        }
    }
}